<template>
  <div class="experimentCreate">
    <el-form :model="form" ref="form" label-width="120px" v-loading="formLoading" element-loading-text="获取数据中"
      element-loading-spinner="el-icon-loading" :rules="rules">
      <el-form-item label="试卷名称" prop="title" required>
        <el-input v-model="form.title" placeholder="请填写试卷名称" />
      </el-form-item>
      <el-form-item label="试卷描述" prop="desc" required>
        <el-input v-model="form.desc" placeholder="请填写试卷描述" />
      </el-form-item>
      <!--el-form-item label="建议时间(min)" prop="suggestedTime" style="text-align:left;" required>
        <el-input-number v-model="form.suggestedTime" label="推荐时间"></el-input-number>
      </el-form-item-->

      <el-form-item label="选择题：" prop="choicesProblem" style="text-align:left">
        <el-button icon="el-icon-plus" type="primary" size="mini" round @click="addQuestion(0)">添加题目</el-button>
        <el-form class="exampaper-item-box" v-if="form.choicesProblem && form.choicesProblem.length !== 0">
          <el-form-item :key="index" v-for="(item, index) in form.choicesProblem" :inline="true">
            <el-col :span="18">
              <el-form-item class="el-form-item-title">
                <span style="color:#909399">题目{{(index + 1)}} </span>
                <el-divider direction="vertical"></el-divider>
                <span>{{ item.id }}.{{ item.title }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
            <el-form-item label="分数(分)" label-width="80px">
              <el-input-number @change="scoreChange" size="mini" placeholder="请填写分数"
                v-model="form.choicesProblem[index].score">
              </el-input-number>
              <el-button type="danger" size="mini" circle icon="el-icon-delete"
                @click="form.choicesProblem.splice(index, 1)">
              </el-button>
              </el-form-item>
            </el-col>
            
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="判断题：" prop="trueOrFalse" style="text-align:left">
        <el-button icon="el-icon-plus" type="primary" size="mini" round @click="addQuestion(1)">添加题目</el-button>
        <el-form class="exampaper-item-box" v-if="form.trueOrFalse && form.trueOrFalse.length !== 0">
          <el-form-item :key="index" v-for="(item, index) in form.trueOrFalse">
            <el-col :span="18">
              <el-form-item class="el-form-item-title">
                <span style="color:#909399">题目{{(index + 1)}} </span>
                <el-divider direction="vertical"></el-divider>
                <span>{{ item.id }}.{{ item.title }}</span>
              </el-form-item>
            </el-col>
            <el-form-item label="分数(分)" label-width="80px">
              <el-input-number @change="scoreChange" size="mini" placeholder="请填写分数"
                v-model="form.trueOrFalse[index].score"></el-input-number>
              <el-button type="danger" size="mini" circle icon="el-icon-delete"
                @click="form.trueOrFalse.splice(index, 1)">
              </el-button>
            </el-form-item>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="编程题：" prop="programmingQuestions" style="text-align:left">
        <el-button icon="el-icon-plus" type="primary" size="mini" round @click="addQuestion(2)">添加题目</el-button>
        <el-form class="exampaper-item-box" :inline="false" v-if="
            form.programmingQuestions && form.programmingQuestions.length !== 0
          ">
          <el-form-item :key="index" v-for="(item, index) in form.programmingQuestions">
            <el-col :span="18">
              <el-form-item class="el-form-item-title">
                <span style="color:#909399">题目{{(index + 1)}} </span>
                <el-divider direction="vertical"></el-divider>
                <span>{{ item.id }}.{{ item.title }}</span>
              </el-form-item>
            </el-col>
            <el-form-item label="分数(分)" label-width="80px">
              <el-input-number @change="scoreChange" size="mini" placeholder="请填写分数"
                v-model="form.programmingQuestions[index].score"></el-input-number>
              <el-button type="danger" size="mini" icon="el-icon-delete" circle
                @click="form.programmingQuestions.splice(index, 1)">
              </el-button>
            </el-form-item>

          </el-form-item>

        </el-form>
      </el-form-item>
      <!--el-form-item label="试卷总分：" v-if="form.score" style="text-align:left">
        {{ form.score }}
      </el-form-item-->
      <el-form-item label="试卷总分：" style="text-align:left">
        {{ getScore }}
      </el-form-item>
      <el-divider></el-divider>
      <el-form-item >
        <el-button type="info" round v-debounce="resetForm" class="reset">重置</el-button>
        <el-button type="primary" round v-debounce="submitForm">提交</el-button>
      </el-form-item>
    </el-form>
    <el-dialog :visible.sync="questionPage.showDialog" width="70%"  @close="close">
      <el-form :model="questionPage.queryParam" ref="queryForm" :inline="true">
        <el-form-item label="题目：">
          <el-input v-model="questionPage.queryParam.title" clearable></el-input>
        </el-form-item>
        <el-form-item style="padding-left:10px;" label="知识点：">
          <el-select v-model="questionPage.queryParam.tag" filterable placeholder="请选择">
            <el-option v-for="item in tags" :key="item.id" :label="item.name" :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-debounce="getQuestions">查询</el-button>
        </el-form-item>
      </el-form>
      <div class="questionList">
        <el-table v-loading="questionPage.listLoading" :data="questionPage.tableData"
          @selection-change="handleSelectionChange" border fit highlight-current-row style="width: 100%">
          <el-table-column type="selection" width="50"></el-table-column>
          <el-table-column prop="id" label="Id" width="60px" />
          <el-table-column prop="title" label="题干" show-overflow-tooltip />
          <el-table-column prop="tag" align="center" label="知识点" width="200px">
            <template v-slot="{ row }">
              <el-tag v-for="item in row.tags" :key="item.index">{{
                item.name
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column sortable align="center" prop="level" label="难度" width="80px">
            <template v-slot="{ row }">
              <span>{{levelChange(row.level)}}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-pagination v-show="questionPage.total > questionPage.queryParam.pageSize" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" :current-page="questionPage.queryParam.pageNum"
        :page-sizes="[5, 10, 20, 30, 50]" :page-size="questionPage.queryParam.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="questionPage.total">
      </el-pagination>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button :loading="submitLoading" type="primary" @click="confirmQuestion">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getAllQuestion,
    getAllTag
  } from "@/api/question.js";
  import {
    addTestPaper,
    updateTestPaper,
    showPaperDetail
  } from "@/api/testpaper.js";
  export default {
    name: "paperCreate",
    data() {
      return {
        tags: [],
        formLoading: false,
        form2: {
          id: 1,
          name: "第一单元测试",
          time: 60, //建议时间
          score: 100,
          items: [{
              type: 0,
              questions: [{
                //题目id(数组)
                id: 1,
                //题目类型(整型) 0代表选择题，1代表判断题，2代表程序题
                type: 0,
                //题干(String)
                title: "课堂管理讲师对课堂气氛的掌握课堂管理讲师对课堂气氛的掌握课堂管理讲师对课堂气氛的掌握课堂管理讲师对课堂气氛的掌握课堂管理讲师对课堂气氛的掌握",
                //题目的选项(数组)
                answer: [{
                    //选项的索引(String)
                    prefix: "A",
                    //选项的内容（String）
                    content: "JAVA"
                  },
                  {
                    prefix: "B",
                    content: "C++"
                  },
                  {
                    prefix: "C",
                    content: "Vue"
                  },
                  {
                    prefix: "D",
                    content: "Php"
                  }
                ],
                //正确答案（String）
                correct: "A",
                //题目难度（整型） 0代表低级  1代表中级  2代表高级
                level: 2,
                //题目对应知识点（String）
                tag: "Java常识"
              }]
            },
            {
              type: 1,
              questions: [{
                //题目id
                id: 2,
                type: 1,
                title: "JAVA是目前全世界使用频率最高的编程语言，JAVA是目前全世界使用频率最高的编程语言，JAVA是目前全世界使用频率最高的编程语言，JAVA是目前全世界使用频率最高的编程语言",
                answer: [{
                    prefix: "A",
                    content: "对"
                  },
                  {
                    prefix: "B",
                    content: "错"
                  }
                ],
                correct: "A",
                level: 1,
                tag: "Java常识"
              }]
            },
            {
              type: 2,
              questions: [{
                //题目id(数组)
                id: 10,
                //题目类型(整型) 0代表选择题，1代表判断题，2代表程序题
                type: 2,
                //题干(String)
                title: "计算a+b的结果",
                //题干描述(String)
                description: "简易的a+b问题，实现一个简单的加法",
                //输入描述(String)
                inputDescription: "输入两个数字a和b，以逗号",
                //输出描述(String)
                outputDescription: "输出a+b的结果",
                //时间限制（整型）,单位ms
                timeLimit: 5000,
                //内存限制（整型）,单位MB
                memoryLimit: 10,
                //题目难度（整型） 0代表低级  1代表中级  2代表高级
                level: "2",
                //题目提示(String
                hint: "输入时，逗号必须是英文输入的逗号;其他提示",
                //题目对应知识点（String）
                tag: "两数加法",
                //输入输出提示（数组）
                ioSamples: [{
                    //输入提示（String）
                    inputSample: "1,2",
                    //输出提示（String）
                    outputSample: "3"
                  },
                  {
                    inputSample: "3,4",
                    outputSample: "7"
                  }
                ],
                //测试数据id（整型），（上传测试数据zip到后台后，后台会返回一个id）
                testCaseId: 1
              }]
            }
          ]
        },
        form: {
          score: 0,
          choicesProblem: [],
          trueOrFalse: [],
          programmingQuestions: []
        },
        rules: {
          name: [{
            required: true,
            message: "请输入试卷名称",
            trigger: "blur"
          }]
        },
        questionPage: {
          tableData: [],
          showDialog: false,
          queryParam: {
            title: null,
            tag: null,
            type: null,
            pageNum: 1,
            pageSize: 5
          },
          multipleSelection: [],
          listLoading: false,
          total: 0
        },
        isAdd: true,
        selectedType: 0,
        currentTitleItem: null,
        timeLimit: [],
        submitLoading: false
      };
    },
    created() {
      this.$route.meta.title = "试卷创建";
      getAllTag().then(res => {
        this.tags = res;
      });
      if (this.$route.query.id) {
        this.formLoading = true;
        let obj={
          testPaperId:this.$route.query.id,
          // examId:99
        }
        showPaperDetail(obj).then((res) => {
          this.form = res.data;
          this.isAdd = false;
          this.$route.meta.title = "编辑试卷";
        }).catch(() => {
          this.$message.error("无法获取试卷数据！");
          this.$router.push({
            name: "testModule/paperlist"
          });
        }).finally(() => {
          this.formLoading = false;
        })

      }
    },
    computed: {
      levelChange() {
        let levels = ["easy", "medium", "hard"];
        return (val) => {
          return levels[val]
        }
      },
      getScore() {
        let score1 = 0;
        let score2 = 0;
        let score3 = 0;
        this.form.programmingQuestions&&this.form.programmingQuestions.map((item,index)=>{
          score1 += item.score; 
        })
        this.form.choicesProblem&&this.form.choicesProblem.map((item,index)=> {
          score2  += item.score;
        })
        this.form.trueOrFalse&&this.form.trueOrFalse.map((item,index)=> {
          score3 += item.score;
        })
        this.form.score = score1 + score2 + score3;
        return this.form.score;
      }
    },
    methods: {
      getTabelData() {},
      scoreChange(currentValue, oldValue) {
        this.form.score = this.form.score + currentValue;
        if (oldValue) {
          this.form.score = this.form.score - oldValue;
        }
      },
      
      addQuestion(index) {
        /* if(!this.form.items)
          {
              this.form.items=new Array(3).fill().map(()=>{return  {type:null,questions:[]}});
          } */
        /* 
          if(index==0)
          {this.questionPage.tableData=this.tableData0,this.selectedType=0}
          else if(index==1)
          {this.questionPage.tableData=this.tableData1,this.selectedType=1}
          else
          {this.questionPage.tableData=this.tableData2,this.selectedType=2} */
        this.questionPage.queryParam.type = index;
        this.questionPage.showDialog = true;
        this.getQuestions();
      },
      getQuestions() {
        this.questionPage.listLoading = true;
        getAllQuestion(this.questionPage.queryParam)
          .then(res => {
            this.questionPage.tableData = res.data;
            this.questionPage.total = res.total;
          })
          .finally(() => {
            this.questionPage.listLoading = false;
          });
      },
      confirmQuestionSelect() {
        let target =
          this.questionPage.queryParam.type == 0 ?
          this.form.choicesProblem :
          this.questionPage.queryParam.type == 1 ?
          this.form.trueOrFalse :
          this.form.programmingQuestions;
        this.questionPage.multipleSelection.forEach(q => {
          if (q.score) delete q.score;
          if (
            !target.some(item => {
              //判断是否含有该题
              if (q.id == item.id) return true;
            })
          ) {
            q.score = 1;
            //不存在则添加进来  避免重复数据
            target.push(q);
          }
        });
        this.questionPage.multipleSelection = [];
      },
      confirmQuestion() {
        this.confirmQuestionSelect();
        this.questionPage.showDialog = false;
        
      },
      close() {
        this.questionPage.showDialog = false;
        this.questionPage.queryParam.pageNum =1;
      },
      handleSelectionChange(val) {
        this.questionPage.multipleSelection = val;
      },
      handleSizeChange(size) {
        this.questionPage.queryParam.pageSize = size;
        this.confirmQuestionSelect();
        this.getQuestions();
      },
      handleCurrentChange(page) {
        this.questionPage.queryParam.pageNum = page;
        this.confirmQuestionSelect();
        this.getQuestions();
      },
      resetForm() {
        this.form = this.$options.data().form;
      },
      submitForm() {
        //数据提交验证
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.submitLoading = true;
            //添加试卷
            //因为接口只需每个题目的id score 先存储数据以防上传失败正常回显
            this.form.creatorId = JSON.parse(localStorage.getItem("user")).userId;
            console.log(this.form.creatorId)
            let question1, question2, question3;
            question1 = this.form.programmingQuestions;
            question2 = this.form.choicesProblem;
            question3 = this.form.trueOrFalse;
            if (this.isAdd) {
              this.form.choicesProblem = this.form.choicesProblem.map(item => {
                let obj = {};
                console.log(2);
                obj.id = item.id;
                obj.score = item.score;
                return obj;
              });
              this.form.programmingQuestions = this.form.programmingQuestions.map(
                item => {
                  console.log(1);
                  let obj = {};
                  obj.id = item.id;
                  obj.score = item.score;
                  return obj;
                }
              );

              this.form.trueOrFalse = this.form.trueOrFalse.map(item => {
                let obj = {};
                obj.id = item.id;
                console.log(3);
                obj.score = item.score;
                return obj;
              });
              addTestPaper(this.form)
                .then(res => {
                  this.$message.success("上传成功！");
                  this.$router.push({
                    name: "testModule/paperlist",
                    params: {
                      mark: true
                    }
                  });
                })
                .catch(() => {
                  this.$message.error("上传失败！");
                  this.form.programmingQuestions = question1;
                  this.form.choicesProblem = question2;
                  this.form.trueOrFalse = question3;
                })
                .finally(() => {
                  this.submitLoading = false;
                });
              return;
            }

            //修改试卷
            delete this.form.delLoading;
            this.form.questionList = [];
            this.form.id = this.$route.query.id;

            this.form.choicesProblem = this.form.choicesProblem.forEach(item => {
              let obj = {};
              obj.problemId = item.id;
              obj.score = item.score;
              obj.type = 0; //type 0  选择题  type1 判断题 type2程序题
              this.form.questionList.push(obj);
            });
            this.form.trueOrFalse = this.form.trueOrFalse.forEach(item => {
              let obj = {};
              obj.problemId = item.id;
              obj.score = item.score;
              obj.type = 1; //判断题
              this.form.questionList.push(obj);
            });

            this.form.programmingQuestions = this.form.programmingQuestions.forEach(
              item => {
                console.log(1);
                let obj = {};
                obj.problemId = item.id;
                obj.score = item.score;
                obj.type = 2; //编程题
                this.form.questionList.push(obj);
              }
            );

            let desc,creatorId,examId;
            desc = this.form.desc;
            creatorId = this.form.creatorId;
            examId = this.form.examId;

            delete this.form.choicesProblem;
            delete this.form.programmingQuestions;
            delete this.form.trueOrFalse;
            delete this.form.creatorId;
            delete this.form.examId;
            
            this.form.description = this.form.desc;
            delete this.form.desc;

            /*let data = {};
            data.id = this.form.id;
            data.questionList = this.form.questionList;
            data.score = this.form.score;
            data.suggestedTime = this.form.suggestedTime;
            data.title = this.form.title;*/

            

            updateTestPaper(this.form)
              .then(res => {
                this.$message.success("编辑成功！");
                this.form.creatorId = creatorId;
                this.form.examId = examId;
                this.form.desc = desc;
                //console.log(data);
                //console.log(this.form);
                this.$router.push({
                  name: "testModule/paperlist",
                  params: {
                    mark: true
                  }
                });
              })
              .catch(() => {
                this.$message.error("编辑失败！");
                console.log(data);
                console.log(this.form);
                delete this.form.questionList;
                this.form.programmingQuestions = question1;
                this.form.choicesProblem = question2;
                this.form.choicesProblem = question3;
              })
              .finally(() => {
                this.submitLoading = false;
              });
          }
        })
      }
    }
  };
</script>
<style scoped>
  .el-form-item-title {
    border: solid 1px #DCDFE6;
    padding-left: 20PX;
  }

  .el-form-item .el-form-item {
    margin-bottom: 5px;
  }
  .reset {
    margin-left: 450px;
  }
  
</style>
